# -*- coding: utf-8 -*-
from utils.utils import *
from utils.config import http_config
import datetime
import time
import json
import requests
import time
import random

null = None
false = False
true = True
def step1():
	# 上报员上报
	print("当前流程:上报员上报信息")
	now = datetime.datetime.now()
	now_time = now.strftime("%m-%d %H:%M:%S")
	token = get_token("06181111111")
	url = "/reporter/submit_potential_info"
	payload = {
		"hospital":"西安交通大学第一附属医院测试1",
		"province":"[\"陕西省\",\"西安市\",\"长安区\"]",
		"department":"急诊",
		"name":f"{now_time}",
		"sex":gender,
		"disease":f"{now_time}测试原发病",
		"blood":"A（RH阴）",
		"location":""
	}
	res = opo_post(url,payload,token)
	if(res['code']==200):

		url = "/reporter/get_case_history"
		payload = {"pageNum":1,"pageSize":8,"donator_name":"%%"}
		res = opo_post(url,payload,token)
		if(res['code']==200):
			case_id = res['data']['list'][0]['case_id']
			print(f"上报员上报成功,case_id:{case_id}")
			return case_id



def step3():
	# 协调员上报
	print("当前流程:协调员上报信息")
	token = get_token("06182222222")
	now = datetime.datetime.now()
	now_time = now.strftime("%m-%d %H:%M:%S")
	url = "/coordinator/submit_potential_info"
	payload = {
		"hospital": "西安交通大学第一附属医院测试1",
		"province": "[\"陕西省\",\"西安市\",\"长安区\"]",
		"department": "ICU",
		"name":f"{now_time}",
		"sex": gender,
		"disease": f"{now_time}测试原发病",
		"blood": "A（RH阴）",
		"area_id": "64",
		"age": age,
		# "id_card": json.dumps(["身份证号",id_number]),
		"id_card": ["身份证号",id_number],
		# 这里直接转str好像还不认
		"donate_hos": "西安交通大学第一附属医院测试2",
		"nation": nation,
		"birth": birth_date
	}

	format_request_payload = format_payload(payload)
	res = opo_post(url,format_request_payload,token)
	if(res['code']==200):
		payload = {
			"flow_list": ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
			"pageNum": "1",
			"pageSize": 6,
			"donator_name": "%%%%",
			"case_code": "%%%%",
			"role": "coordinator"
		}
		url = "/case_utils/coordinator_get_case_list_by_flow"
		res = opo_post(url,payload,token)
		if(res['code']==200):
			case_id = res['data']['list'][0]['case_id']
			print(f"协调员上报成功,case_id:{case_id}")
			return case_id


def step2(case_id):
	# 协调员接受案例＆初步评估
	print("当前流程:协调员接受上报员案例")
	token = get_token("06182222222")
	payload = {
		"case_id":case_id,
		# "fucoordinator_user_id":""
	}
	url = "/coordinator/accept_case"
	res = opo_post(url,payload,token)
	if(res['code']==200):
		print("协调员案例接收成功")
		url = "/api/coordinator/pass_case_first_evulation"
		payload = {
				"case_id": case_id,
				"sex": gender,
				"age": age,
				"id_card": ["身份证号",id_number],
				"donate_hos": "西安交通大学第一附属医院",
				"nation": nation,
				"birth": birth_date
			}
		format_request_payload = format_payload(payload)
		# 主要就是list需要转义
		res = opo_post(url,payload,token)
		if(res['code']==200):
			print("协调员初步评估通过")


def step4(case_id):
	# 评估医师接受案例
	print("当前流程:评估医师接受案例")
	token = get_token("06183333333")
	payload = {
		"case_id":case_id,
		# "fucoordinator_user_id":""
	}
	url = "/evaluator/accept_case"
	res = opo_post(url,payload,token)

	if(res['code']==200):
		print(f"评估医师案例接收成功")


def step5(case_id):
	# 评估医师案例评估
	print("当前流程:评估医师案例评估-表单填写")
	token = get_token("06183333333")
	now = datetime.datetime.now()
	now_time = now.strftime("%m-%d %H:%M:%S")
	url = "/case_utils/get_code_and_name"
	payload = {
		"case_id": case_id
	}
	res = opo_post(url,payload,token)
	if(res['code']==200):
		anlibianhao = res['data']['case_code']

	payload = {
		'case_id':case_id,
		'base_info': {'anlibianhao': anlibianhao, 'xingming': f'{now_time}测试', 'nianling': age, 'xingbie': gender, 'minzu': nation, 'zhengjian': '身份证号', 'shenfenzhenghao': id_number, 'juanxianyiyuan': '西安交通大学第一附属医院测试', 'shengao': '170', 'tizhong': '70', 'BMI': '24.22', 'calculateBMI': '24.22', 'xueya': '100', 'xinlv': '90', 'tiwen': '37', 'huxi': '20'},
		'disease_his': {'gaoxueyashi': '无', 'gaoxueyashiYear': '不用填', 'tangniaobingshi': '无', 'tangniaobingshiYear': '不用填', 'shenbingshi': '无', 'shenbingshiYear': '不用填', 'yinjiushi': '无', 'yinjiushiYear': '不用填', 'xiyanshi': '无', 'xiyanshiYear': '不用填', 'qitabingshi': '无', 'qitabingshiYear': '不用填', 'qitabingshiDisease': '不用填', 'shoushushi': '无', 'shoushushiYear': '不用填', 'shoushushiDisease': '不用填'},
		'death_decide': {'hunmichengdu': '深昏迷', 'zizhuhuxi': '无呼吸', 'shenjingfanshe': '无神经反射', 'huxijishiyong': '没有使用呼吸机', 'GCSpingfen': '10'},
		'hos_stiuation': {'yuanfabing': f'{now_time}测试原发病', 'fabingshijian': '100', 'xinfeifusushi': '否', 'xinfeifusushiNumber': '不用填', 'xinfeifusushiTime': '不用填', 'ICU': '无', 'ICUDay': '不用填', 'niaoliangtian': '100', 'niaoliangxiaoshi': '100', 'dixueyaguocheng': '无', 'dixueyaguocheng100': '不用填', 'dixueyaguocheng80': '不用填', 'dixueyaguocheng50': '不用填', 'shengyayao': '无'},
		'infect_diseases': {'Cr': None, 'BUN': None, 'Ua': None, 'GIU': None, 'Na': None, 'K': None, 'AST': None, 'ALT': None, 'TBIL': None, 'DBIL': None, 'ALB': None, 'baiqiubizhi': None, 'GGT': None, 'CO2CP': None, 'PT': None, 'PO2': None, 'niaodanbaidingxing': None, 'niaodanbai': None, 'niaojigan': None, 'yangbaohedu': None, 'APTT': None, 'niaodanbaijigan': None, 'FIB': None, 'Hb': None, 'WBC': None, 'PLT': None, 'HBV': None, 'HCV': None, 'meidu': None, 'HIV': None, 'PaO2': None, 'FiO2': None, 'PaO2FiO2': None, 'calculatePaO2FiO2': None},
		'pic_check': {'xinzangBchao': '无', 'fubuBchao': '无', 'CTXxian': '无'},
		'result':'通过',
		'donate_type':'DBCD',
		# "big_organ_id": random_big_organ_id_list,
		'death_json':'ss',
		'score_info_json': {'xingming': f'{now_time}测试', 'xingbie': gender, 'nianling': age, 'keshi': 'ICU', 'chuanghao': '测试床号', 'zhuyuanhao': '测试住院号', 'linchuangzhenduan': '可以捐献', 'yiyuan': '西安交通大学第一附属医院测试4'},
		'age_score':'0',
		'disease_score':'0',
		'low_blood_pressure_score':'5',
		'high_blood_pressure_score':'0',
		'jigan_score':'0',
		'cpr_score':'0',
		'total_score':5,
	}

	format_request_payload = format_payload(payload)
	# print(format_request_payload)
	format_request_payload['big_organ_id'] = random_big_organ_id_list
	url = "/evaluator/evaluate_case_insert_sheet"
	res = opo_post(url,format_request_payload,token)
	if(res['code']==200):
		print("评估成功")

def step6(case_id):
	# 评估医师案例评估上传附件
	print("当前流程:评估医师案例评估-附件上传＆通过案例")
	token = get_token("06183333333")
	params = {'case_id': case_id} 
	url = '/evaluator/upload_file'
	params['pic_type'] = "liver_kidney"
	res = opo_upload(url,params,token)
	params['pic_type'] = "blood_type"
	res = opo_upload(url,params,token)
	params['pic_type'] = "infect"
	res = opo_upload(url,params,token)
	params['pic_type'] = "antigen_test"
	res = opo_upload(url,params,token)
	url = "/evaluator/evaluate_case_acceptable"
	payload = {
		'case_id': case_id
	}
	time.sleep(0.1)
	res = opo_post(url,payload,token)
	if(res['code'] == 200):
		print("成功评估通过案例")
	if(res['code'] == 500):
		print("评估表单还未提交")

def step7(case_id):
	# 协调员 json&file混合上传
	print("当前流程:协调员上传亲属同意前表")
	token = get_token("06182222222")

	url = "/coordinator_form_utils/insert_coordinator_family_before_info_sheet"
	payload = {
		"case_id": case_id,
		"accident": "无",
		"relation": '[\"配偶\"]',
		"disease_type": "脑血管意外",
		"result": "同意",
		"will": "志愿登记同意"
	}
	res = opo_mix_upload_step7(url,payload,token)
	if(res['code']==200):
		print("协调员上传亲属同意前表成功")

def step9(case_id):
	# 协调员 
	print("当前流程:协调员-获取手术前完善表/亲属同意后表")
	token = get_token("06182222222")

	url = "/coordinator_form_utils/upload_coordinator_family_after_info_sheet_file"
	payload = {
		"case_id": case_id,
		"country": "中国",
		"id_code": id_number,
		"birthday": birth_date,
		"age": age,
		"nation": nation,
		"degree": "小学",
		"job": "无",
		"jiguan": "[\"陕西省\",\"西安市\",\"长安区\"]",
		"donate_type": "DBCD",
		"obtain_address": "脚本测试医院",
		"big_organ_id": random_big_organ_id_list,
		"coordinator": "",
		"donate_institution": "脚本测试医院",
		"donate_hospital": "脚本测试医院",
		"honghui_coordinator": "红会协调员1（示例工作单位1）"
	}
	res = opo_mix_upload_step9(url,payload,token)
	if(res['code']==200):
		print("协调员亲属同意后表补充完成")

def step8(case_id):
	# 获取医师出发
	print("当前流程:获取医师-案例出发")
	token = get_token("15002954689")
	url = "/obtainer/get_acceptable_case_list"
	payload = {"pageNum":1,"pageSize":5,"donator_name":"%%","task_state":"%0%","case_code":"%%"}
	res	= opo_post(url,payload,token)
	if(res['code']==200):
		for item in res['data']['list']:
			if item['obtainerCaseBaseEntity']['case_id'] == case_id:
				task_id = item['task_id']
				break	
			else:
				print('没有找到case_id对应的task_id')
				return 0;
		url = '/obtainer/accept_case'
		payload = {"case_id":case_id,"task_id":task_id}
		res	= opo_post(url,payload,token)
		if(res['code']==200):
			print("获取医师出发成功")




def step10(case_id):
	# 超管
	print('当前流程:超级管理员-发起伦理审批')
	token = get_token('15249273495')
	url = "/case_super_admin/start_ethical_audit"
	payload = {"case_id":case_id}
	res = opo_post(url,payload,token)
	if(res['code']==200):
		print("发起伦理审批-成功")

def step11(case_id):
	print("当前流程:伦理委员会审批通过")
	token = get_token("123")
	url = '/ethical/ethical_approve_pass'
	payload = {"case_id":case_id}

	res = opo_post(url,payload,token)
	if(res['code']==200):
		token = get_token("18991610106")
		time.sleep(2)
		res = opo_post(url,payload,token)
		if(res['code']==200):
			print("伦理委员会审批-成功")

def step11_2(case_id):
	print("当前流程:伦理委员会审批不通过")
	token = get_token("123")
	url = '/ethical/ethical_approve_fail'
	payload = {"case_id":case_id,"fail_reason":"脚本测试不通过"}
	res = opo_post(url,payload,token)
	if(res['code']==200):
		token = get_token("18991610106")
		time.sleep(2)
		res = opo_post(url,payload,token)
		if(res['code']==200):
			print("伦理委员会审批-成功")

def step12(case_id):
	print("当前流程:协调员-手术开始")
	token = get_token("06182222222")
	url = "/coordinator/start_operation"
	payload = {"case_id":case_id}
	res = opo_post(url,payload,token)
	if(res['code'] == 200):
		print("协调员开始手术-成功")

def step13(case_id):
	token = get_token("15002954689")
	print("当前流程:获取医师-手术结束")


	subcase_big_organ_list = get_subcase_big_organ_info_list(token,case_id)
	# 是json的list

	# 只有下面这几个有质量评估
	# 肾脏:左肾右肾
	# 肝脏
	# 心脏
	# 肺
	json_in_payload = {}
	# json是个库名，规避一下

	checkOrgans = {}
	organsOptions = []
	notGainReason = {}
	choose = True
	check_organ_num = 0
	for big_organ_info in subcase_big_organ_list:
		# print(big_organ_info)
		organ_name = big_organ_info['organ_name']

		checkOrgans[organ_name] = choose
		# 是否选中此器官
		if(choose):
			organsOptions.append(organ_name)
			if(organ_name == "肾脏"):
				# override式的，重复了也没问题
				json_in_payload['kidney1'] = {
						"texture": "硬",
						"textureDegree": "轻度",
						"save": "冷保存",
						"pressure": "",
						"flow": "",
						"resistance": "",
						"length": 111,
						"artery": 1,
						"vein": 1,
						"ureter": "单支",
						"estimate": "正常",
						"biopsy": "否",
						"biopsyResult": "",
						"abnormal": "",
						"allocation": "西安交大一附院",
						"other": ""
				}
				json_in_payload['kidney2'] = {
					"texture": "硬",
					"textureDegree": "轻度",
					"save": "冷保存",
					"pressure": "",
					"flow": "",
					"resistance": "",
					"length": 11,
					"artery": 1,
					"vein": 1,
					"ureter": "单支",
					"estimate": "正常",
					"biopsy": "否",
					"biopsyResult": "",
					"abnormal": "",
					"allocation": "西安交大一附院",
					"other": ""
				}

			if(organ_name == "心脏"):
				json_in_payload['heart'] = {
					"save": "冷保存",
					"pressure": "",
					"flow": "",
					"resistance": "",
					"estimate": "正常",
					"abnormal": "",
					"biopsy": "否",
					"biopsyResult": "",
					"allocation": "西安交大一附院",
					"other": ""
				}
			if(organ_name == "肝脏"):
				json_in_payload["liver"] = {
				"texture": "质软",
				"save": "冷保存",
				"pressure": "",
				"flow": "",
				"resistance": "",
				"estimate": "正常",
				"abnormal": "",
				"allocation": "西安交大一附院",
				"other": ""
			}
			if(organ_name == "肺脏"):
				json_in_payload['lung'] = {
					"save": "冷保存",
					"pressure": "",
					"flow": "",
					"resistance": "",
					"estimate": "正常",
					"abnormal": "",
					"biopsy": "否",
					"biopsyResult": "",
					"allocation": "西安交大一附院",
					"other": ""
				}
		else:
			notGainReason[organ_name] = "大器官未获取理由"
	big_organ_id_list = random_big_organ_id_list
	little_organ_list = get_little_organ_id_list(token,big_organ_id_list)
	# 目前是全选写死
	# print(little_organ_list)
	json_in_payload['checkOrgans'] = checkOrgans
	json_in_payload['organsOptions'] = organsOptions
	json_in_payload['notGainReason'] = notGainReason
	# print(json_in_payload)
	# notGainReason example {"胰腺":""}
	# print(little_organ_list)
	# print(checkOrgans)
	# print(organsOptions)
	# 案例中选中的大器官列表

	'''
	json主要是这几部分
	checkOrgans
	organsOptions
	notGainReason
	获取器官评估
	liver
	...
	kidney1
	不同器官的表单还不太一样
	check_organ_num
	# 穿刺活检器官数量
	little_organ_id_list
	# 选中的移植器官 
	'''

	url = "/obtainer/finish_obtain_operation"
	payload = {
		"case_id": case_id,
		"finish": "已完成",
		"obtain_add": "测试获取地点",
		# 获取地点
		"obtain_man": "测试获取人员",
		# 测试获取人员
		"获取护士":"测试获取护士",
		"json": json.dumps(json_in_payload),
	
		"check_organ_num": check_organ_num,
		# 可移植器官列表
		"little_organ_id_list": little_organ_list
	}


	res = opo_post(url,payload,token)
	if(res['code'] == 200):
		print("获取医师上传手术信息-成功")


def step14(case_id):
	token = get_token("15002954689")
	print("当前流程:获取医师-上传器官获取记录表/手术信息")
	url = "/case_utils/get_big_organ_subcase"
	payload = {"case_id":case_id}	
	res = opo_get(url,payload,token)
	if(res['code'] == 200):
		print("获取医师-器官获取记录表-成功")
		big_organ_list = res['data']
		for big_organ in big_organ_list:
			# print(big_organ)
			big_organ_subcase_id = big_organ['big_organ_subcase_id']
			url = '/obtainer/upload_operation_record_big_organ'
			params = {'big_organ_subacase_id': big_organ_subcase_id, 'is_obtained':'是' }
			opo_mix_upload_step14(url,params,token)

def step15(case_id):
	token = get_token("15002954689")
	print("当前流程:获取医师-选择器官去向")
	url = f"/case_utils/get_little_organ_subcase"
	payload = {"case_id":case_id}	
	res = opo_get(url,payload,token)
	if(res['code'] == 200):
		print("获取医师-移植器官列表获取成功")
		
		little_organ_list = res['data']
		i= 0
		subcase_state_list = ['01','00','11','10']
		for little_organ in little_organ_list:
			# print(big_organ)
			i += 1
			i = i % 4
			time.sleep(2)
			little_organ_id = little_organ['little_organ_subcase_id']
			cold_blood_time = little_organ['cold_blood_time']

			url = '/obtainer/set_little_organ_subcase_state'
			params = {
				"case_id": case_id,
				"little_organ_subcase_id": little_organ_id, 
				"subcase_state":subcase_state_list[i],
				"cold_blood_time": cold_blood_time
			}
			# subcase_state 
			# 01 本院接收
			# 00 本院器用
			# 11 外院接收
			# 10 外院弃用
			opo_post(url,params,token)


def step16(case_id):
	token = get_token("15002954689")
	print("当前流程:获取医师-外院接收")
	now = datetime.datetime.now()
	now_time = now.strftime("%m-%d %H:%M:%S")


	opre_time = now.isoformat(timespec='milliseconds') + 'Z'
	url = "/case_utils/get_little_organ_subcase"
	params = {"case_id":case_id}
	res = opo_get(url,params,token)
	if(res['code'] == 200):
		subcase_list = res['data']
		for subcase in subcase_list:
			if(subcase['subcase_state'] == "11" and subcase['case_id'] == case_id):
				# 外院接收
				little_organ_name = subcase['little_organ_name']
				little_organ_subcase_id = subcase['little_organ_subcase_id']
				print(f"{little_organ_name} 外院接收")
				url = "/obtainer/accept_little_organ_subcase"
				payload = {
					"little_organ_subcase_id": little_organ_subcase_id,
					"name": f"{now_time}测试",
					"is_pilishi": false,
					"sex": gender,
					"blood_type": "A（RH阴）",
					"iden_num": id_number,
					"age": age,
					"jiguan": "陕西省西安市长安区",
					"transplant_hos": "脚本测试医院",
					"department": "肾移植科",
					"opre_time": opre_time,
					"main_doctor": "脚本测试主医师",
					"second_doctor": "脚本测试副医师",
					"transplant_organ": "1"
					# 前面抽的1个，这里就写死为1
				}
				opo_post(url,payload,token)
				time.sleep(2)



def step17(case_id):
	# 外院弃用
	token = get_token("15002954689")
	print("当前流程:获取医师-外院弃用")
	url = "/case_utils/get_little_organ_subcase"
	params = {"case_id":case_id}
	res = opo_get(url,params,token)
	if(res['code'] == 200):
		subcase_list = res['data']
		for subcase in subcase_list:
			if(subcase['subcase_state'] == "10" and subcase['case_id'] == case_id):
				# 本院弃用
				little_organ_name = subcase['little_organ_name']
				little_organ_subcase_id = subcase['little_organ_subcase_id']
				cold_blood_time = subcase['cold_blood_time']
				print(f"{little_organ_name} 外院弃用")
				url = "/obtainer/set_little_organ_subcase_state"
				payload = {
					"case_id":case_id,
					"little_organ_subcase_id":little_organ_subcase_id,
					"subcase_state":"00",
					"cold_blood_time":cold_blood_time
				}
				opo_post(url,payload,token)
				url = "/obtainer/abandon_little_organ_subcase"
				params= {
					"little_organ_subacase_id":little_organ_subcase_id
				}
				opo_mix_upload_step19(url,params,token)
				time.sleep(2)

def step18(case_id):
	print("当前流程:移植医师-本院接收")
	phone_list = ["15929920556","15029094435","12345678905"]
	for phone in phone_list:
		self_accept(phone)


def self_accept(phone):
	token = get_token(phone)
	now = datetime.datetime.now()
	now_time = now.strftime("%m-%d %H:%M:%S")
	formatted_time = now.isoformat(timespec='milliseconds') + 'Z'
	# 2024-12-04T09:41:50.617Z
	url = "/transplant_doctor/get_department_little_organ_subcase_list"
	payload = {
			"pageNum": "1",
			"pageSize": "5",
			"donator_name": "%%%%",
			"case_code": "%%",
			"subcase_state": "01",
			"flow_list": ["1"] 
		}
	res = opo_post(url,payload,token)
	if(res['data']):
		for subcase in res['data']['list']:
			# print(subcase)
			if(subcase['subcase_state'] == "01" and subcase['case_id'] == case_id):
				url = "/obtainer/accept_little_organ_subcase"
				little_organ_name = subcase['littleOrganInfo']['little_organ_name']
				little_organ_subcase_id = subcase['little_organ_subcase_id']
				print(f"{little_organ_name} 本院接收")
				# 本院接收，填表单
				payload = {
					"little_organ_subcase_id": little_organ_subcase_id,
					"name": f"{now_time}测试",
					"is_pilishi": false,
					"sex": gender,
					"blood_type": "A（RH阴）",
					"iden_num": id_number,
					"age": age,
					"jiguan": "陕西省西安市长安区",
					"transplant_hos": "脚本测试医院",
					"department": "肾移植科",
					"opre_time": formatted_time,
					"main_doctor": "脚本",
					"second_doctor": "脚本",
					"transplant_organ": "1"
				}
				opo_post(url,payload,token)
				time.sleep(2)


def step19(case_id):
	# 本院弃用
	token = get_token("15002954689")
	print("当前流程:获取医师-本院弃用")
	url = "/case_utils/get_little_organ_subcase"
	params = {"case_id":case_id}
	res = opo_get(url,params,token)
	if(res['code'] == 200):
		subcase_list = res['data']
		for subcase in subcase_list:
			if(subcase['subcase_state'] == "00" and subcase['case_id'] == case_id):
				# 本院弃用
				little_organ_name = subcase['little_organ_name']
				little_organ_subcase_id = subcase['little_organ_subcase_id']
				cold_blood_time = subcase['cold_blood_time']
				print(f"{little_organ_name} 本院弃用")
				url = "/obtainer/set_little_organ_subcase_state"
				payload = {
					"case_id":case_id,
					"little_organ_subcase_id":little_organ_subcase_id,
					"subcase_state":"00",
					"cold_blood_time":cold_blood_time
				}
				opo_post(url,payload,token)
				url = "/obtainer/abandon_little_organ_subcase"
				params= {
					"little_organ_subacase_id":little_organ_subcase_id
				}
				opo_mix_upload_step19(url,params,token)
				time.sleep(2)




def step20(case_id):
	token = get_token('06182222222')
	print("当前流程:协调员-血样送检")
	url = "/coordinator/blood_check"
	payload = {"case_id": case_id}
	res = opo_post(url,payload,token)
	if(res['code'] == 200):
		print("协调员-血样送检成功")


def step21(case_id):
	token = get_token('13991912927')
	print("当前流程:实验室管理员-接收血样")
	url = "/lab_admin/get_case_need_sample"
	payload = {"pageNum":1,"pageSize":8,"donator_name":"%%","state":"%1%","case_code":"%%"}
	res = opo_post(url,payload,token)
	for item in res['data']['list']:
		if item['case_id'] == case_id:
			sample_id = item['sample_id']
			break	
		else:
			print('没有找到case_id对应的task_id')
			return 0;
	url = "/lab_admin/accept_blood_sample"
	payload = {"__v_isShallow":False,"__v_isRef":True,"_rawValue":{},"_value":{},"sample_id":sample_id}
	res = opo_post(url,payload,token)
	if(res['code'] == 200):
		print("实验室管理员-接收血样成功")

def step22(case_id):
	token = get_token('13991912927')
	print("当前流程:实验室管理员-上传血检结果")
	url = "/lab_admin/update_sample_file"
	payload = {"case_id":case_id}
	res = opo_upload(url,payload,token)
	if(res['code'] == 200):
		print("实验室管理员-上传血检成功")

	


def step23(case_id):
	# 获取结束后完善表
	token = get_token('06182222222')
	print("当前流程:协调员-获取结束后完善表")
	now = datetime.datetime.now()
	now_time = now.strftime("%Y-%m-%d %H:%M")
	death_time = now - datetime.timedelta(days=2,hours=10)
	# obtain_start_time = now - datetime.timedelta(days=2)
	# obtain_end_time = now - datetime.timedelta(days=1)
	# 这里要和下面的
	url = "/coordinator_form_utils/insert_coordinator_supplement_sheet"
	payload = {
		"case_id": case_id,
		"hos_number": "测试住院号",
		"death_time": death_time.strftime("%Y-%m-%d %H:%M"),
		# "2024-12-04 15:28"这三个都是这种格式
		# "obtain_start_time": obtain_start_time.strftime("%Y-%m-%d %H:%M"),
		"obtain_start_time": iso_timestamp_format(operaBeginTime),
		# "obtain_end_time": obtain_end_time.strftime("%Y-%m-%d %H:%M"),
		"obtain_end_time": iso_timestamp_format(operaEndTime),
		"main_family_name": "测试家庭成员",
		"relationship": "[\"配偶\"]",
		"phone": phone,
		"address": "陕西省西安市长安区",
		"confirm": null,
		"remains_recovered": "是",
		"remembrance_ceremony": "是",
		"remains_whereboat": "太平间"
	}
	print(f"协调员,手术开始时间{iso_timestamp_format(operaBeginTime)}")
	# print(payload)
	res = opo_mix_upload(url,payload,token)
	if(res['code'] == 200):
		print("获取结束后完善表填写成功")

def step24(case_id):
	token = get_token("15002954689")
	print("当前流程:获取医师-填写信息补充表")
	print(f"获取医师,手术开始时间{operaBeginTime}")
	subcase_big_organ_list = get_subcase_big_organ_info_list(token,case_id)
	# 是json的list

	payload = {
		"case_id": case_id,
		"hot_blood_time": "测试热缺血时间",
		# 不是时间戳
		"bianyuan_organ_id": random_big_organ_id_list,
		"bianyuan_organ": random_big_organ_list,
		# 这里直接怼随机的相当于全选
		"organ_donate_case_record_json": {
			"gender": gender,
			"age": age,
			"birth": birth_date,
			"ethnicOption": nation,
			"nativePlace": [
				"陕西省",
				"西安市",
				"长安区"
			],
			# 籍贯
			"nationality": "中国",
			"marriage": "未婚",
			"career": "无",
			"postalCode": 1,
			"choseIdenType": "身份证号",
			"workUnit": 1,
			"hospitalization": "否",
			"spHosp": "",
			"vaccination": "否",
			"relationP": [
				"父"
			],
			"relationC": [],
			"sun": "",
			"daughter": "",
			"brother": "",
			"sister": "",
			"contact": 1,
			"contactRela": 1,
			"contactPhone": 1,
			"contactAddr": 1,
			"dateToHos": dateToHos,
			# 入院时间 2024-12-04T06:51:10.977Z
			"dateToOffice": dateToOffice,
			# 入科时间 2024-12-04T06:51:10.977Z
			"dateToWrite": dateToWrite,
			# 书写时间 2024-12-04T06:51:10.977Z
			"primaryDisease": "测试原发病",
			# 原发病
			"primaryDiseaseDate": primaryDiseaseDate,
			# 原发病发病时间
			"coma": "深昏迷",
			"breath": "有",
			"breathMachine": "否",
			"reflex": "有",
			"hypertension": "无",
			"hypertensionYear": "",
			"cardiopathy": "无",
			"cardiopathyYear": "",
			"diabetes": "无",
			"diabetesYear": "",
			"Cerebrovascular": "无",
			"CerebrovascularDiag": "",
			"CerebrovascularYear": "",
			"tumour": "无",
			"liverFailure": "无",
			"kidneyFailure": "无",
			"smokingHis": "无",
			"drinkingHis": "无",
			"operationHis": "无",
			"operation": "",
			"CPRhis": "无",
			"CPRnum": "",
			"CPRtime": "",
			"IDHhis": "无",
			"IDH100": "",
			"IDH80": "",
			"IDH50": "",
			"urineH": 11,
			"urine24H": 11,
			"others": "无",
			"otherDisease": "",
			"valueT": 1,
			"valueP": 1,
			"valueR": 1,
			"valueR1": 1,
			"valueR2": 1,
			"valueBp": 1,
			"height": 170,
			"weight": 60,
			"valueBMI": 23,
			"KidneyFuncDate": KidneyFuncDate,
			"KidneyFuncSCr": 1,
			"KidneyFuncBUN": 1,
			"KidneyFuncUa": 1,
			"liverFuncDate": liverFuncDate,
			"liverFuncAST": 1,
			"liverFuncALT": 1,
			"liverFuncTBIL": 1,
			"liverFuncDBIL": 1,
			"liverFuncALB": 1,
			"electrolyteDate": electrolyteDate,
			"electrolyteNa": 1,
			"electrolyteK": 1,
			"electrolyteCl": 1,
			"electrolyteCO": 1,
			"DicDate": DicDate,
			"DicPT": 1,
			"DicAPTT": 1,
			"DicFIB": 1,
			"DicDD": 1,
			"CbcDate": CbcDate,
			"CbcHb": 1,
			"CbcWBC": 1,
			"CbcPLT": 1,
			"CbcCRP": 1,
			"UaDate": UaDate,
			"UaWBC": 1,
			"UaRBC": 1,
			"UaPro": 1,
			"infectiousDate": infectiousDate,
			"infectiousHBV": "阴性",
			"infectiousHCV": "阴性",
			"infectiousHIV": "阴性",
			"infectiousPRP": "阴性",
			"AboDate": AboDate,
			"Abo": 1,
			"AboRhD": "阴性",
			"microbeDate": microbeDate,
			"microbe": 1,
			"imagingDate": imagingDate,
			"imagingLiver": 1,
			"imagingkidney": 1,
			"imagingHeart": 1,
			"imagingLung": 1
		},
		"donate_record_json": {
			"livingWill": true,
			"relativesWill": true,
			"brainDeath": true,
			"heartDeath": true,
			"agreeState": 1,
			"hospital": 1,
			"operation": 1,
			"operatorDoctor": 1,
			"organType": [True for _ in range(len(random_big_organ_list))],
			# 根据index的一个布尔列表
			"other": "",
			# 下面这几个全是2024-12-04T07:11:38.137Z
			# "operaBeginDate": operaBeginDate,
			"operaBeginTime": operaBeginTime,
			# "perfusionDate": perfusionDate,
			# 灌注时间好像是
			"perfusionTime": perfusionTime,
			# "operaEndDate": operaEndDate,
			"operaEndTime": operaEndTime
		},
		"start_time": start_time,
		"guanzhu_time": guanzhu_time,
		"death_record_json": {
			"donateType": "DBD",
			"brainDeath": {
				"place": 1,
				"clinicalBrainDeath": {
					"date": death_time,
					"time": death_time,
					"doctorFirst": 1,
					"doctorSecond": 1,
					"result": "符合"
				},
				"checkItems": {
					"eegCheck": true,
					"evoCheck": true,
					"craCheck": true
				},
				"eegExamination": {
					"date": death_time,
					"time": death_time,
					"result": "符合"
				},
				"evokedPotentialExamination": {
					"date": death_time,
					"time": death_time,
					"result": "符合"
				},
				"cranialDopplerUltrasound": {
					"date": death_time,
					"time": death_time,
					"result": "符合"
				},
				"spontaneousRespirationStimulationTest": {
					"date": death_time,
					"time": death_time,
					"doctorFirst": 1,
					"doctorSecond": 1,
					"result": "符合"
				}
			},
			"heartDeath": {
				"date": "",
				"time": "",
				"hospital": "",
				"heartStopMinute": "",
				"unrecoveredMinute": "",
				"deathTime": ""
			}
		}
	}
	url = "/obtain_form_utils/insert_obtain_supplement_sheet"
	format_request_payload = format_payload(payload)
	res = opo_post(url,format_request_payload,token)
	if(res['code'] == 200):
		print("获取医师-填写信息补充表成功")

def step25(case_id):
	token = get_token("15002954689")
	print("当前流程:获取医师-发起归档")
	payload = {
		"case_id": case_id
		}
	url = "/obtainer/archive"
	res = opo_post(url,payload,token)
	if(res['code'] == 200):
		print("获取医师-发起归档成功")

def step26(case_id):
	print("当前流程：超级管理员-补充术后恢复信息")
	token = get_token("15249273495")
	url = "/case_utils/get_little_organ_subcase"
	params = {"case_id":case_id}
	res = opo_get(url,params,token)
	if(res['code'] == 200):
		for little_organ in res['data']:
			# print(little_organ)
			if(little_organ['acceptor_recover'] == "未完成" ):
				print(little_organ['little_organ_name'])
				little_organ_subcase_id = little_organ['little_organ_subcase_id']
				# 这里应该是先用little_organ_subcase_id查acceptor_info_id
				url = "/obtainer/get_accept_little_organ_subcase_info"

				params = {"little_organ_subcase_id": little_organ_subcase_id}
				res = opo_get(url,params,token)
				if(res['code'] == 200):
					acceptor_info_id = res['data'][0]['acceptor_info_id']
					# 这里存疑，返回的是个list，但是目前遇到的length都只有1，可能是接口复用？
					# print(acceptor_info_id,len(res['data']))

					url = "/obtainer/update_accept_little_organ_subcase_info"

					payload = {
							"acceptor_info_id": acceptor_info_id,
							# 这个哪来的？？？
							"is_pilishi": false,
							"sex": gender,
							"blood_type": "A（RH阴）",
							"age": age,
							"jiguan": "陕西省西安市长安区",
							"transplant_hos": "医院1",
							"department": "肾移植科",
							"opre_time": convert_time_format(opre_time),
							# "2024-12-04T14:30:03.000+00:00"
							"main_doctor": "脚本测试",
							"second_doctor": "脚本测试",
							"transplant_organ": "6",
							"updater": "张静",
							"recover": null,
							"baseInfoCodeJson": null,
							"form1_recover": "正常恢复",
							"little_organ_subcase_id": little_organ_subcase_id
						}
					opo_post(url,payload,token)
					time.sleep(1)
					url = "/case_super_admin/set_recover"
					payload = {
						"little_organ_subcase_id":little_organ_subcase_id,
						"acceptor_info_id":acceptor_info_id,
						"recover":"正常恢复"
					}
					opo_post(url,payload,token)
					time.sleep(1)

def step27(case_id):
	print("当前流程：超级管理员-审核归档")
	token = get_token("15249273495")
	url = f"/case_super_admin/archive?case_id={case_id}"
	payload = {
		"case_id":case_id
	}
	# 这个其实没用上，参数在query里，这么写是懒得改util
	res = opo_post(url,payload,token)
	if(res['code']==200):
		print("超级管理员-归档成功")



def summon_global_organ_list(n):
	'''
	保证唯一性，生成一个全局变量的organ_id_list
	'''
	token = get_token("15249273495")
	big_organ_list,big_organ_id_list = get_big_organ(token)
	big_organ_num = len(big_organ_list)
	print(f"逻辑存在大器官数量:{big_organ_num}")
	indices = list(range(len(big_organ_list)))
	if(n>big_organ_num):
		print("抽取数量超过逻辑存在大器官数量")
	else:
		random_indices = random.sample(indices,n)

		random_big_organ_id_list = [big_organ_id_list[i] for i in random_indices]
		random_big_organ_list = [big_organ_list[i] for i in random_indices]
		return random_big_organ_list,random_big_organ_id_list

if __name__ == '__main__':
	# 大器官部分
	random_organ_num = 2
	# 随机抽取大器官数
	random_big_organ_list,random_big_organ_id_list = summon_global_organ_list(random_organ_num)
	# 全局的organ_id_list

	# 身份证部分
	id_number = generate_random_id_number()
	info_dict = analysis_id_number(id_number)
	age = info_dict['age']
	gender = info_dict['gender']
	birth_date = info_dict['birth_date']
	print(birth_date)
	# print(birth_date)
	nation = info_dict['nation']
	phone = "12345678910"



	# 时间戳部分
	current_time = datetime.datetime.now()

	# 计算3天前的时间
	three_days_ago = current_time - datetime.timedelta(days=3)

	# 按照指定格式将3天前的时间转换为字符串
	start_time_str = three_days_ago.strftime('%Y-%m-%d %H:%M:%S')

	end_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
	iso_timestamps = generate_random_timestamp(start_time_str,end_time_str)
	print(iso_timestamps)
	# "primaryDisease": "测试原发病"
	# 原发病
	dateToHos = generate_random_timestamp(start_time_str,end_time_str)
	# "dateToHos": "2024-12-04T06:51:10.977Z",
	# 入院时间 2024-12-04T06:51:10.977Z
	dateToOffice = generate_random_timestamp(start_time_str,end_time_str)
	# "dateToOffice": "2024-12-11T06:51:12.902Z",
	# 入科时间 2024-12-04T06:51:10.977Z
	dateToWrite = generate_random_timestamp(start_time_str,end_time_str)
	# "dateToWrite": "2024-12-03T06:51:14.073Z",
	# 书写时间 2024-12-04T06:51:10.977Z
	primaryDiseaseDate = generate_random_timestamp(start_time_str,end_time_str)
	# "primaryDiseaseDate": "2024-12-04T06:51:17.167Z",
	# 原发病发病时间
	KidneyFuncDate = generate_random_timestamp(start_time_str,end_time_str)
	# KidneyFuncDate
	liverFuncDate = generate_random_timestamp(start_time_str,end_time_str)
	# liverFuncDate
	electrolyteDate = generate_random_timestamp(start_time_str,end_time_str)
	# electrolyteDate
	DicDate = generate_random_timestamp(start_time_str,end_time_str)
	# DicDate
	CbcDate = generate_random_timestamp(start_time_str,end_time_str)
	# CbcDate
	UaDate = generate_random_timestamp(start_time_str,end_time_str)
	# UaDate
	infectiousDate = generate_random_timestamp(start_time_str,end_time_str)
	# infectiousDate
	AboDate = generate_random_timestamp(start_time_str,end_time_str)
	# AboDate
	microbeDate = generate_random_timestamp(start_time_str,end_time_str)
	# microbeDate
	imagingDate = generate_random_timestamp(start_time_str,end_time_str)
	# imagingDate
	operaBeginDate = generate_random_timestamp(start_time_str,end_time_str)
	# "operaBeginDate": "2024-12-04T07:11:38.137Z",
	operaBeginTime = generate_random_timestamp(start_time_str,end_time_str)
	# "operaBeginTime": "2024-12-02T09:26:47.000Z",
	perfusionDate = generate_random_timestamp(start_time_str,end_time_str)
	# "perfusionDate": "2024-12-18T07:11:42.573Z",
	perfusionTime = generate_random_timestamp(start_time_str,end_time_str)
	# "perfusionTime": "2024-12-04T07:11:47.000Z",
	operaEndDate = generate_random_timestamp(start_time_str,end_time_str)
	# "operaEndDate": "2024-12-11T07:11:54.502Z",
	operaEndTime = generate_random_timestamp(start_time_str,end_time_str)
	# "operaEndTime": "2024-12-04T07:12:47.000Z"

	# 相当混乱啊
	start_time = int(time.time() * 1000) - 10000
	# "start_time": 1741684748086,
	guanzhu_time = int(time.time() * 1000)
	# "guanzhu_time": 1741684748086,
	

	# 死亡记录表部分的
	death_date = generate_random_timestamp(start_time_str,end_time_str)
	# "date": "2024-12-04T07:10:17.019Z",
	death_time = generate_random_timestamp(start_time_str,end_time_str)
	# "time": "2024-12-04T07:14:12.000Z",
	opre_time = generate_random_timestamp(start_time_str,end_time_str)
	# 手术时间



	# print(id_number)
	# case_id = step1()
	# case_id = "1516"
	# step2(case_id)
	# test()

	case_id= '1747'
	case_id = step3()
	print(case_id)

	step4(case_id)
	step5(case_id)
	step6(case_id)
	step7(case_id)
	step8(case_id)
	step9(case_id)


	step10(case_id)
	step11(case_id)
	# 11 和 11_2 是互斥的
	# step11_2(case_id)

	step12(case_id)
	step13(case_id)
	step14(case_id)
	step15(case_id)
	step16(case_id)
	step17(case_id)
	step18(case_id)
	step19(case_id)

	step20(case_id)
	step21(case_id)
	step22(case_id)
	step23(case_id)


	step24(case_id)


	step25(case_id)
	step26(case_id)
	step27(case_id)
